package com.demo.task;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.demo.common.model.TbProject;
import com.demo.common.model.TbUser;
import com.demo.common.model.TbTask;
import com.demo.tbuser.TbUserService;
import com.demo.util.DateUtils;
import com.demo.util.DateVO;
import com.demo.util.SessionUtil;
import com.demo.vo.TbWeekReportVO;
import com.demo.weekreport.*;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 任务管理
 */
public class TaskController extends Controller {

	@Inject
    TaskService service;

	public void index() {
		Boolean complete = getParaToBoolean("complete", false);
		Boolean important = getParaToBoolean("important",true);
		Boolean emergency = getParaToBoolean("emergency",false);

		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		Integer pageNumber = getParaToInt("page", 1);
		Page<TbTask> paginate = getTbWeekReportPage(startTime, endTime,complete,important,emergency, pageNumber,10);
		Date now = new Date();
		for (TbTask tbTask : paginate.getList()) {
			int daysDate = 0;
			/**
			 * 已完成任务
			 */
			if (tbTask.getEndTime() != null){
				daysDate = DateUtils.getDaysDate(tbTask.getStartTime(), tbTask.getEndTime());
			}else {
				daysDate = DateUtils.getDaysDate(tbTask.getStartTime(), now);
			}
			tbTask.put("duringTime",daysDate);
		}
		setAttr("page", paginate);
		setAttr("startTime",startTime);
		setAttr("endTime",endTime);
		setAttr("complete",complete);
		setAttr("important",important);
		setAttr("emergency",emergency);
		render("index.html");
	}


	/**
	 * 导出的时候 用同样的处理逻辑 只是pageSize搞大一点就行了
	 * @param startTime
	 * @param endTime
	 * @param pageNumber
	 * @return
	 */
	private Page<TbTask> getTbWeekReportPage(String startTime, String endTime,Boolean complete,Boolean important,Boolean emergency, Integer pageNumber, Integer pageSize) {
		//日期默认加在当前周的日志
		DateVO nowDateVO = DateUtils.getNowDateVO();

		List<Object> paramValue = new ArrayList<Object>();
		String condition = "";

		condition = condition + " and complete=?";
		paramValue.add(complete);

		condition = condition + " and important=?";
		paramValue.add(important);

		condition = condition + " and emergency=?";
		paramValue.add(emergency);

		if(!StringUtils.isEmpty(startTime)){
//			startTime = nowDateVO.getMon();
			condition = condition + " and reportDate>=?";
			paramValue.add(startTime);
		}


		if(!StringUtils.isEmpty(endTime)){
//			endTime = nowDateVO.getSun();
			condition = condition + " and reportDate<=?";
			paramValue.add(endTime);
		}

		return service.paginate(pageNumber, pageSize, condition, paramValue);
	}

	@Inject
	TbUserService userService;
	public void add() {
		List<Record> users = userService.getList();
		setAttr("users",users);
	}


	public void copy() throws Exception {
		Integer projectId = getParaToInt("id");
		TbTask obj = service.findById(projectId);
		obj.setId(null);
		obj.setContent("描述");
		obj.setSummary("备注");

		//copy一个任务变成自己
		TbUser tbUser = SessionUtil.getTbUser(getSession());
		obj.setCreatorId(tbUser.getId());
		obj.setUserId(null);
		obj.setUserName(null);

		Date date = new Date();
		obj.setReportDate(date);
		obj.setUpdateTime(date);
		obj.setCreateTime(date);
		obj.setTitle(UUID.randomUUID().toString());
		obj.save();
		redirect("/task");
	}
	/**
	 * 象限模式
	 */
	public void xiangXian(){
		Page<TbTask> paginate_1 = getTbWeekReportPage("", "",false,true,true, 1,20);
		setAttr("page_1", paginate_1);
		Page<TbTask> paginate_2 = getTbWeekReportPage("", "",false,true,false, 1,20);
		setAttr("page_2", paginate_2);
		Page<TbTask> paginate_3 = getTbWeekReportPage("", "",false,false,false, 1,20);
		setAttr("page_3", paginate_3);
		Page<TbTask> paginate_4 = getTbWeekReportPage("", "",false,false,true, 1,20);
		setAttr("page_4", paginate_4);
		render("xiangXian.html");
	}

	/**
	 * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
	 * 并要对数据进正确性进行验证，在此仅为了偷懒
	 */
	public void save() {
		TbTask bean = getBean(TbTask.class);

		Date now = new Date();
		bean.setCreateTime(now);
		bean.setUpdateTime(now);
		bean.setReportDate(now);

		//创建者
		TbUser tbUser = SessionUtil.getTbUser(getSession());
		bean.setCreatorId(tbUser.getId());
//		TbUser tbUser = SessionUtil.getTbUser(getSession());
//		bean.setUserId(tbUser.getId());
//		bean.setUserName(tbUser.getRealName());
		bean.save();
		redirect("/task");
	}

	public void edit() {
		//获取index页面的查询参数，放入隐藏表单,update方法跳转的时候带上，
		Boolean complete = getParaToBoolean("complete", false);
		Boolean important = getParaToBoolean("important");
		Boolean emergency = getParaToBoolean("emergency");

		TbTask tbTask = service.findById(getParaToInt());
		setAttr("tbTask", tbTask);

		setAttr("complete",complete);
		setAttr("important",important);
		setAttr("emergency",emergency);

		List<Record> users = userService.getList();
		setAttr("users",users);
	}

	public void getTask() {
		synchronized (this){
			TbTask byId = service.findById(getParaToInt());
			if (byId.getUserId() != null){
				setAttr("errorMessage","此任务已经被领取");
				redirect("/task/xiangXian");
			}

			TbUser tbUser = SessionUtil.getTbUser(getSession());
			byId.setUserId(tbUser.getId());
			byId.setUserName(tbUser.getRealName());
			Date now = new Date();
			byId.setUpdateTime(now);
			byId.setStartTime(now);
			byId.update();
			redirect("/task/xiangXian");
		}

	}

	/**
	 * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
	 * 并要对数据进正确性进行验证，在此仅为了偷懒
	 */
	public void update() {
		TbTask bean = getBean(TbTask.class);

		Date now = new Date();
		if(bean.getComplete() != null && bean.getComplete()){
			bean.setEndTime(now);
		}
		/**
		 * bug表单 获取的 reportDate如果有修改，两个值都传过来了
		 */
		String[] parameterValues = getRequest().getParameterValues("tbTask.reportDate");
		if (parameterValues.length == 2){
			String reportDate = parameterValues[1];
			Date date = DateUtils.parseDate(DateUtils.YYYYMMDD, reportDate);
			bean.setReportDate(date);
		}
		bean.setUpdateTime(now);
		bean.update();


		Boolean complete = getParaToBoolean("complete", false);
		Boolean important = getParaToBoolean("important");
		Boolean emergency = getParaToBoolean("emergency");
		String url = "/task?complete=%b&important=%b&emergency=%b";
		String formatUrl = String.format(url, complete, important, emergency);
		redirect(formatUrl);
	}

	public void delete() {
		service.deleteById(getParaToInt());
		redirect("/task");
	}

	//////////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * JDK 日期函数  https://mp.weixin.qq.com/s/az40Pa0BAXepCR4aiLan-g
	 * @throws IOException
	 */
    public void download() throws IOException {
		LocalDate localDate = LocalDate.now();
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
		String format = localDate.format(dateTimeFormatter);
		String sheetName = format +"_平台组-工作周报";

        HttpServletResponse response = getResponse();
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(sheetName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		Integer pageNumber = getParaToInt("page", 1);
		Page<TbTask> paginate = getTbWeekReportPage(startTime, endTime,true,true,true, pageNumber,100);
		List<TbTask> list = paginate.getList();

		//转换到 VO list
		List<TbWeekReportVO> result = list.stream().map(temp -> {
			TbWeekReportVO obj = new TbWeekReportVO();
			obj.setUserName(temp.getUserName());
			obj.setContent(temp.getContent());
			obj.setSummary(temp.getSummary());
			obj.setReportDate(temp.getReportDate());
			return obj;
		}).collect(Collectors.toList());

		EasyExcel.write(response.getOutputStream(), TbWeekReportVO.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet(sheetName).doWrite(result);
    }

    private List<DemoData> data() {
        List<DemoData> list = new ArrayList<DemoData>();
        for (int i = 0; i < 10; i++) {
            DemoData data = new DemoData();
            data.setString("字符串" + i);
            data.setDate(new Date());
            data.setDoubleData(0.56);
            list.add(data);
        }
        return list;
    }

    /**
     * 文件上传
     * <p>1. 创建excel对应的实体对象 参照{@link UploadData}
     * <p>2. 由于默认异步读取excel，所以需要创建excel一行一行的回调监听器，参照{@link UploadDataListener}
     * <p>3. 直接读即可
     */
    public String upload() throws IOException {
        UploadFile file = getFile();
        EasyExcel.read(new FileInputStream(file.getFile()), UploadData.class, new UploadDataListener(null)).sheet().doRead();
        return "success";
    }

    public void statistics(){
		Boolean complete = getParaToBoolean("complete", false);
		Boolean important = getParaToBoolean("important",null);
		Boolean emergency = getParaToBoolean("emergency",null);

		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		Map map = new HashMap<>();
		map.put("complete",complete);
		map.put("startTime",startTime);
		map.put("endTime",endTime);
		List<Record> list = service.statistics(map);
		setAttr("list", list);
		setAttr("startTime",startTime);
		setAttr("endTime",endTime);
		setAttr("complete",complete);
		setAttr("important",important);
		setAttr("emergency",emergency);

		render("statistics/index.html");
	}
    public void statisticsBak(){
		render("statistics/index-bak.html");
	}
}


